package com.meiyou.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.meiyou.pojo.Coordinate;
import com.meiyou.pojo.DongTai;
import com.meiyou.pojo.DongtaiDianzan;
import com.meiyou.pojo.MeiyouDongtai;
import com.meiyou.pojo.MeiyouUser;
import com.meiyou.pojo.NewPinglun;
import com.meiyou.pojo.vo.DianZanUser;
import com.meiyou.pojo.vo.DongtaiBo;
import com.meiyou.pojo.vo.DongtaiVo;
import com.meiyou.pojo.vo.PingLunBo;
import com.meiyou.pojo.vo.PinglunUser;
import com.meiyou.service.DongtaiService;
import com.meiyou.service.NewPinglunService;
import com.meiyou.service.UserService;
import com.meiyou.utils.Context;
import com.meiyou.utils.IdGenerator;
import com.meiyou.utils.Msg;
import com.meiyou.utils.TimeDifference;
import com.meiyou.utils.jedis.JedisClient;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import redis.clients.jedis.GeoRadiusResponse;

@Controller
@Api(value = "用户动态接口", tags = { "用户动态接口" })
@RequestMapping("/dongtai")
public class DongTaiController {

	@Autowired
	JedisClient jedisClient;
	@Autowired
	DongtaiService dongtaiService;
	@Autowired
	NewPinglunService newPinglunService;
	@Autowired
	UserService userService;
	
	
	//附近动态 
	@RequestMapping(value="/adddongtai",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="用户发布动态",notes="用户发布动态",httpMethod="POST")
	public Msg exit(@RequestParam("mfile") MultipartFile[] mfile,double jindu,double weidu,String account,String tConte,HttpServletRequest req) throws IOException {
		//附近动态 --经度、纬度、用户名、 主体内容、图片视频
		if(StringUtils.isBlank(account) && StringUtils.isBlank(tConte)) {
			return Msg.fail().add("msg", "用户名或主体信息不能为空");
		}
		String id = IdGenerator.get();
		//把经度、纬度、动态Id保存进redis
		Coordinate coordinate = new Coordinate();
		coordinate.setLatitude(weidu);
		coordinate.setLongitude(jindu);
		coordinate.setKey(id+"");
		jedisClient.addReo(coordinate, "dongtai");
		//把动态数据保存进数据库 
		//把文件上传到本地
		//保存到数据库中的相对路径
		/*String uploadPathDB = file.getOriginalFilename();
		String typeName = uploadPathDB.substring(uploadPathDB.indexOf(".") + 1);
		System.out.println(typeName);
		String finalVideoPath = ""; 
		//这里用输入输出流来控制文件的上传
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		//判断文件是否为空
		try{
			if(file!=null){		
				//获取文件名字
			    String fileName = file.getOriginalFilename();
				//判断名字是否为空
				if(fileName!=null){
				   //文件新名字
				   fileName = StringId.genImageName();
				   //文件上传的最终保存路径
				   finalVideoPath = "C://meiyou"+"/images/"+fileName+"."+typeName;
				   uploadPathDB = fileName+"."+typeName;
					//创建文件
				   File outFile = new File(finalVideoPath);
				   if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
					//创建父文件夹
						outFile.getParentFile().mkdirs();
					}					
					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
						IOUtils.copy(inputStream, fileOutputStream);
					}else {
							return Msg.fail().add("msg", "上传出错！！！");
					}
				}
			} catch (Exception e) {
					e.printStackTrace();
					return Msg.fail().add("msg", "上传出错！！！！");
			}finally {
					if(fileOutputStream!=null) {
						fileOutputStream.flush();
						fileOutputStream.close(); 
					}
			}*/
		//这里mfile可以接受前台的文件，可以是一个，也可以是多个，这正是MultipartFile强大的地方。
		HashMap<String, String> map=new HashMap<String, String>();
		//建一个Map便于返回json
		String filePath =null;
		String fileName[]=new String[mfile.length];
		Date date=new Date();
		//根据传递文件个数返回文件（{msg1:"sss.png",msg2:"aa.jpg"}
		String file = "[";
		if (mfile != null && mfile.length > 0) {
		//判断使用有文件上传
			for (int i = 0; i < mfile.length; i++) {
				//循环上传（多文件上传）
				try {
					Calendar cale = null;	
					cale = Calendar.getInstance();
					int year = cale.get(Calendar.YEAR);
					int month = cale.get(Calendar.MONTH) + 1;
					int day = cale.get(Calendar.DATE);
					String address = Context.fwqaddress;
					//给图片重命名加上日期前缀
					filePath= req.getSession().getServletContext().getRealPath("/") ;
					//获取服务器img文件夹地址（这里指的是local:8080/项目名/img）
					fileName[i]= "/imgs/" + year + ""+ month + "" + day + "_" + mfile[i].getOriginalFilename();
					//重命名图片。
					String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
					//截取文件后缀判断是否是一张图片
					if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
						int length = mfile[i].getBytes().length;
						if (!((length / 1000) > 5120)) {
							
							//判断图片地址
							map.put("msg"+i, fileName[i]);
							//将图片输出到制定的文件夹目录中
							mfile[i].transferTo(new File(filePath,fileName[i]));
							if(i==mfile.length-1){
								file +="\""+address+fileName[i]+"\"]";
							}else{
								file +="\""+address+fileName[i]+"\",";
							}
						}else{
							map.put("msg", "图片过大");
						}}else{
						map.put("msg", "只能上传图片啊亲!");}
				} catch (Exception e) {
					e.printStackTrace();
					map.put("msg", "上传失败");}}} else {
			map.put("msg", "请选择文件");}
		DongTai dongtai = new DongTai();
		Date time = new Date();
		dongtai.setId(id);
		dongtai.settContent(tConte);
		dongtai.settUcount(account);
		dongtai.settYuedu(0);
		dongtai.settImgorVideo(file);
		dongtai.settTime(time); 
		//保存进数据库 
	    dongtaiService.insert(dongtai);
		return Msg.success();  
	}
	
	//修改附近动态观看次数
	@RequestMapping(value="/updatecishu",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="修改观看次数",notes="修改观看次数",httpMethod="POST")
	public Msg updatecishu(String dongtaiId){
		dongtaiService.updatecishu(dongtaiId); 
		return Msg.success();
	}
	
	
	//根据登录用户经纬度查询附近动态
	@RequestMapping(value="/selectdongtai",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据经纬度查询动态",notes="根据经纬度查询动态",httpMethod="POST")
	public Msg selectdongtai(double jindu,double weidu,String account,HttpServletRequest req,int userId){
		System.out.println("打死米ffaf");
	    System.out.println(jindu+"||"+weidu+"||"+userId); 
		Coordinate coordinate = new Coordinate();
		coordinate.setLatitude(weidu);
		coordinate.setLongitude(jindu);
		List<GeoRadiusResponse> list = jedisClient.geoQuery(coordinate, 100,"dongtai");
		List<DongtaiVo> ls = new ArrayList<DongtaiVo>();
		
		if(list!=null && list.size()!=0) {
			for(GeoRadiusResponse geo:list) {
				//System.out.println(geo.getMemberByString());
				DongTai dongtaiTemp = dongtaiService.selectById(geo.getMemberByString());
				if(dongtaiTemp==null){
				}else{
					System.out.println(dongtaiTemp);
					System.out.println("地址"+dongtaiTemp.gettImgorVideo());
					JSONArray array = JSONArray.parseArray(dongtaiTemp.gettImgorVideo());
					
					//System.out.println(dongtaiTemp); 
					DongtaiVo dongtai = new DongtaiVo();
					
					dongtai.setArray(array);
					MeiyouUser user =  dongtaiService.selectUserById(dongtaiTemp.gettUcount());
				    System.out.println("user:"+user.toString());
				    dongtai.setAge(user.getuOld());
				    dongtai.setHeaderImg(user.getuImg());
				    dongtai.setNickname(user.getuName());
					if(dongtaiTemp!=null) {
						//是本人就不显示
						if(!account.equals(dongtaiTemp.gettUcount())) {
							String time="";
							BeanUtils.copyProperties(dongtaiTemp, dongtai);
							Date newtime = new Date();
						    TimeDifference timeDifference = new TimeDifference();
						    List<Long> listtime = timeDifference.getTimeDifference(newtime,dongtaiTemp.gettTime()); //工具类获取两个时间差值
						    if(listtime.get(0)==0) {
						    	if(listtime.get(1)==0) {
						    		if(listtime.get(2)==0) {
						    			time = listtime.get(3)+"秒前";
						    		}else {
						    			time = listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    		}
						    	}else {
						    		time = listtime.get(1)+"小时"+listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    	}
						    }else {
						    	time = listtime.get(0)+"天"+listtime.get(1)+"小时"+listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    }
						    DecimalFormat    df   = new DecimalFormat("######0.00");
						    String juli = df.format(geo.getDistance());
						    dongtai.setJuli(juli);
						    dongtai.setTime(time);
						    
						    //获取评论数和点赞数 
						    /*List<Pinglun> listpinglun = dongtaiService.selectAllPinglun(dongtai.getId());
						    dongtai.setPinglunshu(listpinglun.size()); */
						    List<DongtaiDianzan> listdianzan = newPinglunService.selectDongtaidianzanById(dongtai.getId());
						    List<NewPinglun> listpinglun = newPinglunService.selectDongtaiPinglunById(dongtai.getId());
						    if(listdianzan==null){
						    	dongtai.setDianzan(0);
						    }else{
						    	dongtai.setDianzan(listdianzan.size());
						    }
						    
						    if(listpinglun==null){
						    	dongtai.setPinglunshu(0);
						    }else{
						    	dongtai.setPinglunshu(listpinglun.size());
						    }
						    
						    //判断当前用户是否点赞
						    DongtaiDianzan dongtaiDianzan = new DongtaiDianzan();
							dongtaiDianzan.setDianzanUserId(userId);
							dongtaiDianzan.setDongtaiId(dongtaiTemp.getId());
						    List<DongtaiDianzan> list2 = dongtaiService.panduanshifoudianzan(dongtaiDianzan);
							if(list2.size()>0){
								dongtai.setIsdianzan(true);
							}else{
								dongtai.setIsdianzan(false);
							}
						    
						    System.out.println("动态"+dongtai);
						    ls.add(dongtai);
						}
					}
				}
			}	
			return Msg.success().add("list", ls);
		}else {
			return Msg.success().add("msg", "暂时没有附近动态");  
		}
	}
	
	//根据用户ID查询用户信息
	@RequestMapping(value="/selectUserById",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据用户ID查询用户信息",notes="根据用户ID查询用户信息",httpMethod="POST")
	public Msg selectUserById(String uccount){
		
		MeiyouUser user = dongtaiService.selectUserById(uccount);
		return Msg.success().add("user", user);
	}
	
	//根据用户账号查询所有动态
	@RequestMapping(value="/selectDongtaiByuccount",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据用户ID查询用户信息",notes="根据用户ID查询用户信息",httpMethod="POST")
	public DongTai selectDongtaiByuccount(String uccount){
		DongTai selectDongtaiByuccount = dongtaiService.selectDongtaiByuccount(uccount);
		JSONArray array = JSONArray.parseArray(selectDongtaiByuccount.gettImgorVideo());
		selectDongtaiByuccount.setArray(array);
		return selectDongtaiByuccount;
	}
	
	
	
	//根据动态Id查询动态信息（最新）
	@RequestMapping(value="/selectDongtaiByDongtaiId",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据动态Id查询动态信息(最新)",notes="根据动态Id查询动态信息(最新)",httpMethod="POST")
	public Msg selectDongtaiByDongtaiId(String dongtaiId,int userId){
		
		System.out.println(dongtaiId+"||"+userId);
		//首先查询出都动态信息 然后查询出用户信息 点赞数 评论数
		MeiyouDongtai dongTai = dongtaiService.selectDongtaiByDontaiId(dongtaiId);
		System.out.println(dongTai);
		//查询用户信息 根据用户名
		MeiyouUser user = dongtaiService.selectUserByaccount(dongTai.gettUcount());
		System.out.println(user);
		//查询点赞数
		int dianzan = 0;
		List<DongtaiDianzan> list= newPinglunService.selectDongtaidianzanById(dongtaiId);
		if(list.size()>0){
			dianzan = list.size();
		}
		//查询评论数
		int pinglun = 0;
		 List<NewPinglun> list1 = newPinglunService.selectDongtaiPinglunById(dongtaiId);
		 if(list.size()>0){
			 pinglun = list1.size();
		 }
		 
		 DongtaiBo bo = new DongtaiBo();
		 //判断是否点赞    查询动态点赞表是否有信息
		 DongtaiDianzan dongtaiDianzan = new DongtaiDianzan();
		 dongtaiDianzan.setDianzanUserId(userId);
		 dongtaiDianzan.setDongtaiId(dongtaiId);
		 List<DongtaiDianzan> list2 = dongtaiService.panduanshifoudianzan(dongtaiDianzan);
		 if(list2.size()>0){
			 bo.setIsdianzan(true);
		 }else{
			 bo.setIsdianzan(false);
		 }
		// DongtaiBo bo = new DongtaiBo();
		 bo.setDianzan(dianzan);
		 bo.setDongTai(dongTai);
		 bo.setPinglun(pinglun);
		 bo.setUser(user);
		 
		return Msg.success().add("dongtai", bo);
	}

	//根据动态Id查询评论（最新）
	@RequestMapping(value="/selectPinglunByDongtaiId",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据动态Id查询评论(最新)",notes="根据动态Id查询评论(最新)",httpMethod="POST")
	public Msg selectPinglunByDongtaiId(String dongtaiId){
		
		
		List<PingLunBo> list = dongtaiService.selectPinglunByDongtaiId(dongtaiId);
		return Msg.success().add("list", list);
	}
	
	//根据用户名查询出所有动态(最新)
	@RequestMapping(value="/selectAllDongtaiByAccount",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据用户名查询出所有动态(最新)",notes="根据用户名查询出所有动态(最新)",httpMethod="POST")
	public Msg selectAllDongtaiByAccount(String account){
		
		List<MeiyouDongtai> list = dongtaiService.selectAllDongtaiByAccount(account);
		return Msg.success().add("list", list);
	}
	
	
	//根据性别筛选动态（最新）
	@RequestMapping(value="/selectAllDongtaiBySex",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据性别筛选动态（最新）",notes="根据性别筛选动态（最新）",httpMethod="POST")
	public Msg selectAllDongtaiBySex(double jindu,double weidu,String account,String sex,int userId, HttpServletRequest req){
		
		Coordinate coordinate = new Coordinate();
		coordinate.setLatitude(weidu);
		coordinate.setLongitude(jindu);
		List<GeoRadiusResponse> list = jedisClient.geoQuery(coordinate, 100,"dongtai");
		List<DongtaiVo> ls = new ArrayList<DongtaiVo>();
		
		if(list!=null && list.size()!=0) {
			for(GeoRadiusResponse geo:list) {
				//System.out.println(geo.getMemberByString());
				DongTai dongtaiTemp = dongtaiService.selectById(geo.getMemberByString());
				if(dongtaiTemp==null){
				}else{
					System.out.println(dongtaiTemp);
					System.out.println("地址"+dongtaiTemp.gettImgorVideo());
					JSONArray array = JSONArray.parseArray(dongtaiTemp.gettImgorVideo());
					
					//System.out.println(dongtaiTemp); 
					DongtaiVo dongtai = new DongtaiVo();
					dongtai.setArray(array);
					if(dongtaiTemp!=null) {
						//是本人就不显示
						if(!account.equals(dongtaiTemp.gettUcount())) {
							String time="";
							BeanUtils.copyProperties(dongtaiTemp, dongtai);
							Date newtime = new Date();
						    TimeDifference timeDifference = new TimeDifference();
						    List<Long> listtime = timeDifference.getTimeDifference(newtime,dongtaiTemp.gettTime()); //工具类获取两个时间差值
						    if(listtime.get(0)==0) {
						    	if(listtime.get(1)==0) {
						    		if(listtime.get(2)==0) {
						    			time = listtime.get(3)+"秒前";
						    		}else {
						    			time = listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    		}
						    	}else {
						    		time = listtime.get(1)+"小时"+listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    	}
						    }else {
						    	time = listtime.get(0)+"天"+listtime.get(1)+"小时"+listtime.get(2)+"分"+listtime.get(3)+"秒前";
						    }
						    DecimalFormat    df   = new DecimalFormat("######0.00");
						    String juli = df.format(geo.getDistance());
						    dongtai.setJuli(juli);
						    dongtai.setTime(time);
						    
						    //查询出用户信息根据account
						    
						   MeiyouUser user =  dongtaiService.selectUserByaccount(dongtaiTemp.gettUcount());
						   dongtai.setSex(user.getuSex());
						    //获取评论数和点赞数 
						    List<DongtaiDianzan> listdianzan = newPinglunService.selectDongtaidianzanById(dongtai.getId());
						    List<NewPinglun> listpinglun = newPinglunService.selectDongtaiPinglunById(dongtai.getId());
						    if(listdianzan==null){
						    	dongtai.setDianzan(0);
						    }else{
						    	dongtai.setDianzan(listdianzan.size());
						    }
						    
						    if(listpinglun==null){
						    	dongtai.setPinglunshu(0);
						    }else{
						    	dongtai.setPinglunshu(listpinglun.size());
						    }
						    
						  //判断当前用户是否点赞
						    DongtaiDianzan dongtaiDianzan = new DongtaiDianzan();
							dongtaiDianzan.setDianzanUserId(userId);
							dongtaiDianzan.setDongtaiId(dongtaiTemp.getId());
						    List<DongtaiDianzan> list2 = dongtaiService.panduanshifoudianzan(dongtaiDianzan);
							if(list2.size()>0){
								dongtai.setIsdianzan(true);
							}else{
								dongtai.setIsdianzan(false);
							}
						    ls.add(dongtai);
						}
					}
				}
			}	
			//栓选男女
			
			for(int i = 0; i<ls.size();i++){
				if(!(ls.get(i).getSex().equals(sex))){
					ls.remove(i);
				}
				
			}
			return Msg.success().add("list", ls);
		}else {
			return Msg.success().add("msg", "暂时没有附近动态");  
		}
	}
	
	
	
	//查询未通知动态点赞（最新）
		@RequestMapping(value="/selectNotDongtaiDianzan",method=RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value="查询未通知动态点赞（最新）",notes="查询未通知动态点赞（最新）",httpMethod="POST")
		public Msg selectDongtaiDianzan(int userId){
			
			List<DianZanUser> result = dongtaiService.selectIsNotReadDontaiDianzan(userId);
			return Msg.success().add("result", result);
		}
		
		
		//查询未通知的动态评论(最新)
		@RequestMapping(value="/selectNotDontaiPinglun",method=RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value="查询未通知的动态评论(最新)",notes="查询未通知的动态评论(最新)",httpMethod="POST")
		public Msg selectNotDontaiPinglun(int userId){
			List<PinglunUser> result = dongtaiService.selectIsNotReadPinglun(userId);
			return Msg.success().add("result", result);
		}
		
		
		//查询未通知的评论点赞(最新)
		@RequestMapping(value="/selectNotPinglunDianzan",method=RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value="查询未通知的评论点赞(最新)",notes="查询未通知的评论点赞(最新)",httpMethod="POST")
		public Msg selectNotPinglunDianzan(int userId){
			
			List<DianZanUser> result = dongtaiService.selectIsNotReadPinglunById(userId);
			return Msg.success().add("result", result);
		}

}
